package cn.sfrog.common.utils;


import java.util.stream.IntStream;

/**
 * 身份证号工具类
 *
 */
public class IdentificationCodeUtil2 {

    /**
     * 身份证校验码
     */
    private static final int[] COEFFICIENT_ARRAY = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};

    /**
     * 身份证号的尾数规则
     */
    private static final String[] IDENTITY_MANTISSA = {"1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"};

    private static final String IDENTITY_PATTERN_15 = "^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0-2]\\d)|3[0-1])\\d{3}$";

    // 修改前未做X位的校验："^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0-2]\\d)|3[0-1])\\d{4}$";
    // 修改后："^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0-2]\\d)|3[0-1])\\d{3}[0-9Xx]$";
    private static final String IDENTITY_PATTERN_18 = "^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0-2]\\d)|3[0-1])\\d{3}[0-9Xx]$";


    /**
     * 身份证号校验
     */
    public static boolean isLegalIdCard(String identity) {
        if (identity == null) {
            return false;
        }
        if (identity.length() == 15) {
            return is15BitLegalIdCard(identity);
        }
        if (identity.length() == 18) {
            return is18BitLegalIdCard(identity);
        }
        return false;
    }

    public static boolean is15BitLegalIdCard(String identity) {
        return identity.matches(IDENTITY_PATTERN_15);
    }

    public static boolean is18BitLegalIdCard(String identity) {
        if (identity.length() != 18) {
            return false;
        }
        if (!identity.matches(IDENTITY_PATTERN_18)) {
            return false;
        }
        // 将字符串对象中的字符转换为一个字符数组
        char[] chars = identity.toCharArray();
        long sum = IntStream.range(0, 17).map(index -> {
            char ch = chars[index];
            // 通俗理解：digit()是个边界值判断，不过边界返回字符数字本身数值，超过边界即返回 -1.
            int digit = Character.digit(ch, 10);
            int coefficient = COEFFICIENT_ARRAY[index];
            return digit * coefficient;
        }).summaryStatistics().getSum();

        // 计算出的尾数索引
        int mantissaIndex = (int) (sum % 11);
        String mantissa = IDENTITY_MANTISSA[mantissaIndex];

        String lastChar = identity.substring(17);
        return lastChar.equalsIgnoreCase(mantissa);
    }

    public static void main(String[] args) {
        boolean legalIdCard1 = isLegalIdCard("370781199809254816");
        boolean legalIdCard2 = isLegalIdCard("370781199809254817");
        boolean legalIdCard3 = isLegalIdCard("130503670401001");
        System.out.println(legalIdCard1);
        System.out.println(legalIdCard2);
        System.out.println(legalIdCard2);
    }
}
